//
//  BookSortView.swift
//  KoiAccounting
//
//  Created by 纪洪文 on 04.04.25.
//

import SwiftUI

struct BookSortView: View {
    
    @Environment(\.presentToast) var presentToast
    
    @StateObject var viewModel = BookSortViewModel()
    
    var body: some View {
        VStack {
            List {
                ForEach(viewModel.books.indices, id: \.self) { index in
                    let book = viewModel.books[index]
                    BookItemView(book: book, viewType: .sort)
                        .koiListRowClear()
                        .koiItemRowStyle()
                }
                .onMove(perform: move)
                if viewModel.books.isEmpty {
                    Spacer()
                }
            }
            .listStyle(.plain)
            .padding(EdgeInsets(top: 0, leading: 20, bottom: 0, trailing:20)) // 去除边距
            .ignoresSafeArea(.container, edges: .bottom)
            .scrollContentBackground(.hidden)
            .background(Color.koiColorBackground)
            .overlay(Group {
                if viewModel.books.isEmpty {
                    ZStack {
                        Color.koiColorBackground.ignoresSafeArea()
                    }
                }
            })
        }
        .koiToolbar(title: Text("账本排序"))
        .onChange(of: viewModel.sortState) { newValue in
            if (newValue == "success") {
                viewModel.sortState = ""
                presentToast(.init(message: "排序完成"))
                viewModel.loadBooks()
            }
        }
        .onAppear {
            viewModel.loadBooks()
        }
    }
    
    private func move(from source: IndexSet, to destination: Int) {
        viewModel.books.move(fromOffsets: source, toOffset: destination)
        viewModel.updateBookOrder(from: source, to: destination)
    }
}

#Preview {
    BookSortView()
}
